package cn.ad.server.web.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import java.io.IOException;
import java.io.InputStream;

/**
 * Created by Administrator on 2016/3/24.
 */
public class JsonUtils {
    private static ObjectMapper MAPPER;

    private static ObjectMapper multiMapper;

    static {
        MAPPER = new ObjectMapper();
        MAPPER.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        MAPPER.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
        MAPPER.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
        MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        MAPPER.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
        MAPPER.enable(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT);
    }

    /**
     * java对象转换成json
     */
    public static <T> String toJson(T pojo) {
        String result;
        try {
            result = MAPPER.writeValueAsString(pojo);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("json转换异常", e);
        }
        return result;
    }

    /**
     * java对象转换成json
     */
    public static <T> T toObject(InputStream is, Class<T> clazz) {
        T result;
        try {
            result = MAPPER.readValue(is, clazz);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("json转换异常", e);
        } catch (IOException e) {
            throw new RuntimeException("json转换异常", e);
        }
        return result;
    }

    /**
     * json转换成Java对象
     */
    public static <T> T fromJson(String json, Class<T> valueType) {
        T t;
        try {
            t = MAPPER.readValue(json, valueType);
        } catch (IOException e) {
            throw new RuntimeException("json转换异常", e);
        }
        return t;
    }

}
